package org.webscale.json;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.webscale.ApplicationController;



/**
 * Servlet implementation class for Servlet: JSONServlet
 *
 */
 public class JSONServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	
	 private static final Logger log = Logger.getLogger(JSONServlet.class.getName());
	 private static final long serialVersionUID = -1305501839940993379L;
	 private static final String SPRING_PROPERTIES_LOCATION = "spring.properties.location";
	 public static final String REQUEST_ID = "json-request-id";
	 public static final String JSON_REQUEST_STRING = "json-request-string";

	
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		String propfileLocation = config.getInitParameter(SPRING_PROPERTIES_LOCATION);
		try{
			Properties p = loadProperties(config);
			ApplicationController.instance().setStartUpParamenters(p);
			ApplicationController.instance().init();
			}catch (Exception e) {
				log.severe("JSON Servelet Init Failed");
				log.log(Level.SEVERE , e.getMessage() , e);
				//TODO: Handler this properly
				throw new ServletException(e);
			}
	}

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public JSONServlet() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processHTTPRequest(request , response);
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processHTTPRequest(request , response);
	}   	  
	
	
	protected void processHTTPRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		String requestID = request.getParameter(REQUEST_ID);
		
		if(requestID == null){
			 showErrorPage("No Request ID" , request ,response);
			 return;
		}
		
		
		//TODO: Add a layer for Authorization here
		
		JsonRequestHandler handler = JsonRequestHandler.Factory.create(requestID);
		if(handler == null){
			 showErrorPage("Could Find a Handler for REQUEST="+requestID , request ,response);
			 return;
		}
		
		String jsonResponse = handler.executeRequest(request.getParameter(JSON_REQUEST_STRING));
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println(jsonResponse);
		out.close();
		
	
			log.fine("RETURNING VALUE ***");
			log.fine(jsonResponse);
	
	}
	
	
	private void showErrorPage(String msg ,HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<H3> Error : </H3>");
		out.println("<H4> " + msg + "</H2>");
		out.close();
		log.severe(msg);
	
	}

	private Properties loadProperties(ServletConfig config) throws IOException{
		Properties prop = new Properties();
		Enumeration e = config.getInitParameterNames();
		while(e.hasMoreElements()){
			String key = e.nextElement().toString();
			String value = config.getInitParameter(key);
			prop.put(key, value);
		}
		return prop;
	}
}
